const express = require("express");
const router = express.Router();
const pool = require("./db"); // 假设您有一个 db.js 文件用于连接 MySQL
const path = require("path");
const jwt = require("jsonwebtoken");
const { v4: uuidv4 } = require("uuid");

const { upload } = require("./utils/upload");

const axios = require("axios");

// 注册接口
router.post("/register", (req, res) => {
    const { username, password, name } = req.body;

    // 验证用户名是否已存在
    const query = "SELECT * FROM user WHERE username = ?";
    pool.query(query, [username], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            if (result.length > 0) {
                // 用户名已存在
                res.json({ code: 400, message: "用户名已存在" });
            } else {
                // 用户名不存在，可以注册
                const id = uuidv4();
                const query =
                    "INSERT INTO user (id,username, password, name) VALUES (?,?,?,?)";
                pool.query(
                    query,
                    [id, username, password, name],
                    (err, result) => {
                        if (err) {
                            console.log(err);
                            res.json({ code: 500, message: "服务器内部错误" });
                        } else {
                            res.json({ code: 200, message: "注册成功" });
                        }
                    }
                );
            }
        }
    });
});

// 登录接口
router.post("/login", (req, res) => {
    const { username, password } = req.body;
    // console.log(req.body);
    // 查询数据库
    const query = "SELECT * FROM user WHERE username = ? AND password = ?";
    pool.query(query, [username, password], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            if (result.length > 0) {
                const token = jwt.sign({ username }, "your_secret_key", {
                    expiresIn: "1h",
                });
                const userid = result[0].id;
                // 登录成功
                res.json({ code: 200, message: "登录成功", token, userid });
            } else {
                // 登录失败
                res.json({ code: 401, message: "用户名或密码错误" });
            }
        }
    });
});

// 获取用户说说接口
router.get("/user/shuoShuo", (req, res) => {
    // 获取请求中的用户userid
    const userid = req.query.userid;
    const query = "SELECT * FROM shuoshuo WHERE u_id = ?";
    pool.query(query, [userid], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            function getShuoshuoListWithCallbacks(result, callback) {
                let processed = 0;
                if (result.length === 0) {
                    callback([]);
                    return;
                }
                const shuoshuoList = result.map((item) => {
                    const query =
                        "SELECT avatar_url, name FROM user WHERE id = ?";
                    const shuoshuo = { ...item };

                    pool.query(query, [item.u_id], (err, result2) => {
                        if (err) {
                            console.error(err);
                        } else {
                            shuoshuo.u_avatar_url = result2[0].avatar_url;
                            shuoshuo.u_name = result2[0].name;
                        }

                        processed++;
                        if (processed === result.length) {
                            callback(shuoshuoList);
                        }
                    });

                    return shuoshuo;
                });
            }

            // 使用方式
            getShuoshuoListWithCallbacks(result, (shuoshuoList) => {
                // console.log("处理完成:", shuoshuoList);
                // 在这里继续处理 shuoshuoList
                res.json({
                    code: 200,
                    message: "获取成功",
                    data: shuoshuoList,
                });
            });
        }
    });
});

// 根据说说id获取点赞的人
router.get("/shuoShuo/like", (req, res) => {
    // 获取请求中的说说id
    const shuoshuo_id = req.query.shuoshuo_id;
    const query = "SELECT * FROM shuoshuo_dianzan WHERE shuoshuo_id = ?";
    pool.query(query, [shuoshuo_id], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "获取成功", data: result });
        }
    });
});

// 根据说说id获取评论信息列表
router.get("/shuoShuo/comment", (req, res) => {
    // 获取请求中的说说id
    const shuoshuo_id = req.query.shuoshuo_id;
    const query = "SELECT * FROM shuoshuo_pinglun WHERE shuoshuo_id = ?";
    pool.query(query, [shuoshuo_id], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "获取成功", data: result });
        }
    });
});

// 根据userid获取用户信息
router.get("/user/info", (req, res) => {
    // 获取请求中的用户id
    const userid = req.query.userid;
    const query = "SELECT * FROM user WHERE id = ?";
    pool.query(query, [userid], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "获取成功", data: result });
        }
    });
});

// 根据userid更新用户名
router.put("/user/username", (req, res) => {
    // 获取请求中的用户id和用户名
    const { userid, name } = req.body;
    const query = "UPDATE user SET name = ? WHERE id = ?";
    pool.query(query, [name, userid], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "更新成功" });
        }
    });
});

// 根据userid更新用户密码
router.put("/user/password", (req, res) => {
    // 获取请求中的用户id和密码
    const { userid, currentPassword, newPassword } = req.body;
    const query = "SELECT * FROM user WHERE id = ? AND password = ?";
    pool.query(query, [userid, currentPassword], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            if (result.length > 0) {
                const query = "UPDATE user SET password = ? WHERE id = ?";
                pool.query(query, [newPassword, userid], (err, result) => {
                    if (err) {
                        console.log(err);
                        res.json({ code: 500, message: "服务器内部错误" });
                    } else {
                        res.json({ code: 200, message: "密码更新成功" });
                    }
                });
            } else {
                res.json({ code: 401, message: "当前密码错误" });
            }
        }
    });
});

// 上传头像接口
router.post("/user/avatar", upload.single("avatar"), async (req, res) => {
    if (!req.file) {
        return res
            .status(400)
            .json({ code: 400, message: "请选择要上传的图片" });
    }
    const filename = `http://localhost:3000/images/avatar/${req.file.filename}`;

    // 更新用户头像
    const query = "UPDATE user SET avatar_url = ? WHERE id = ?";
    pool.query(query, [filename, req.body.userid], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({
                code: 200,
                message: "头像上传成功",
                data: { avatar_url: filename },
            });
        }
    });
});

// 根据说说id插入评论
router.post("/shuoShuo/comment", (req, res) => {
    // 获取请求中的说说id和评论内容
    const { shuoshuo_id, u_id, content, date } = req.body;
    const query =
        "INSERT INTO shuoshuo_pinglun (shuoshuo_id,u_id, content, date) VALUES (?,?,?,?)";
    pool.query(query, [shuoshuo_id, u_id, content, date], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "评论成功" });
        }
    });
});

// 根据说说id和点赞人姓名删除点赞情况
router.delete("/shuoShuo/like", (req, res) => {
    // 获取请求中的说说id和点赞人姓名
    const { shuoshuo_id, u_id } = req.body;
    const query =
        "DELETE FROM shuoshuo_dianzan WHERE shuoshuo_id = ? AND u_id = ?";
    pool.query(query, [shuoshuo_id, u_id], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "删除成功" });
        }
    });
});

// 根据说说id和点赞人姓名添加点赞情况
router.post("/shuoShuo/like", (req, res) => {
    // 获取请求中的说说id和点赞人姓名
    const { shuoshuo_id, u_id } = req.body;
    const query =
        "INSERT INTO shuoshuo_dianzan (shuoshuo_id, u_id) VALUES (?,?)";
    pool.query(query, [shuoshuo_id, u_id], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "点赞成功" });
        }
    });
});

// 获取所有说说列表
router.get("/shuoShuo/list", (req, res) => {
    const query = "SELECT * FROM shuoshuo";
    pool.query(query, (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            function getShuoshuoListWithCallbacks(result, callback) {
                let processed = 0;
                const shuoshuoList = result.map((item) => {
                    const query =
                        "SELECT avatar_url, name FROM user WHERE id = ?";
                    const shuoshuo = { ...item };

                    pool.query(query, [item.u_id], (err, result2) => {
                        if (err) {
                            console.error(err);
                        } else {
                            shuoshuo.u_avatar_url = result2[0].avatar_url;
                            shuoshuo.u_name = result2[0].name;
                        }

                        processed++;
                        if (processed === result.length) {
                            callback(shuoshuoList);
                        }
                    });

                    return shuoshuo;
                });
            }

            // 使用方式
            getShuoshuoListWithCallbacks(result, (shuoshuoList) => {
                // console.log("处理完成:", shuoshuoList);
                // 在这里继续处理 shuoshuoList
                res.json({
                    code: 200,
                    message: "获取成功",
                    data: shuoshuoList,
                });
            });
        }
    });
});

// 根据说说id获取说说的图片列表
router.get("/shuoShuo/pic", (req, res) => {
    // 获取请求中的说说id
    const shuoshuo_id = req.query.shuoshuo_id;
    const query = "SELECT img_url FROM shuoshuo_picture WHERE shuoshuo_id = ?";
    pool.query(query, [shuoshuo_id], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "获取成功", data: result });
        }
    });
});

// 根据用户id获取说说所有图片列表
router.get("/user/pic", (req, res) => {
    // 获取请求中的用户id
    const userid = req.query.userid;
    const query = "SELECT img_url FROM shuoshuo_picture WHERE u_id = ?";
    pool.query(query, [userid], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "获取成功", data: result });
        }
    });
});

const multer = require("multer");
// 设置存储引擎
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "public/images/shuoshuo"); // 保存文件的目录
    },
    filename: function (req, file, cb) {
        cb(null, uuidv4() + path.extname(file.originalname)); // 文件名
    },
});

// 初始化 multer
const upload2 = multer({ storage: storage });

// 处理文件上传
router.post("/uploadImages", upload2.array("image", 9), (req, res) => {
    // console.log(req.files);
    // 如果大于9张
    if (req.files.length > 9) {
        return res.json({ code: 400, message: "图片数量不能超过9张" });
    }
    // 成功
    res.json({ code: 200, message: "文件上传成功", files: req.files });
});

// 发布说说的接口，需要u_id,text_content,u_avatar_url.u_name
router.post("/shuoShuo/release", (req, res) => {
    const { u_id, text_content } = req.body;
    const query =
        "INSERT INTO shuoshuo (shuoshuo_id,u_id,date,text_content,browser_count) VALUES (default,?,?,?,?)";
    pool.query(query, [u_id, new Date(), text_content, 0], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            // 返回shuoshuo_id
            res.json({
                code: 200,
                message: "发布成功",
                shuoshuo_id: result.insertId,
            });
        }
    });
});

// 根据说说id和图片url和用户id插入图片信息
router.post("/shuoShuo/pic", (req, res) => {
    // 获取请求中的说说id和图片url和用户id
    const { shuoshuo_id, img_url, u_id } = req.body;
    const query =
        "INSERT INTO shuoshuo_picture (shuoshuo_id,img_url,u_id) VALUES (?,?,?)";
    pool.query(query, [shuoshuo_id, img_url, u_id], (err, result) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: "服务器内部错误" });
        } else {
            res.json({ code: 200, message: "图片上传成功" });
        }
    });
});

// 获取所有好友列表
router.get("/friend/list", async (req, res) => {
    try {
        const { userid } = req.query;

        const sql = `SELECT * FROM user WHERE id != ?`;
        pool.query(sql, [userid], (err, result) => {
            if (err) {
                console.log(err);
                res.json({ code: 500, message: "服务器内部错误" });
            } else {
                res.json({ code: 200, message: "获取成功", data: result });
            }
        });
    } catch (error) {
        console.log(error);
        res.json({ code: 500, message: "服务器内部错误" });
    }
});

// 获取百度AI的token
router.get("/baidu-token", async (req, res) => {
    try {
        const response = await axios.post(
            "https://aip.baidubce.com/oauth/2.0/token",
            null,
            {
                params: {
                    grant_type: "client_credentials",
                    client_id: "Ht5v3zef7Svzy0mHdNGzfgdq",
                    client_secret: "RJSw6vY3iuU8qFOI4x8E4osPpzyCZ0ZA",
                },
            }
        );
        res.json(response.data);
    } catch (error) {
        res.status(500).json({ error: "Failed to get Baidu AI token" });
    }
});

module.exports = router;
